import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../layout/Home.vue'
import Login from '../views/Login.vue'
import MainBox from '../views/dashboard'
import local from '@/utils/local.js'

Vue.use(VueRouter)

// 解决ElementUI导航栏中的vue-router在3.0版本以上重复点菜单报错问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  {
    path: '/',
    component: Home,
    redirect: '/dashboard',
    children: [
      {
        path: '/dashboard',
        meta: { name: '首页' },
        component: MainBox
      },
      {
        path: '/stage/:id',
        meta: { name: '学科列表' },
        component: () =>
          import(/* webpackChunkName: "Error" */ '../views/StageList')
      },
      {
        path: '/pro/:id',
        meta: { name: '项目列表' },
        component: () =>
          import(/* webpackChunkName: "Error" */ '../views/ProList')
      },
      {
        path: '/detail/:id',
        meta: { name: '详情展示' },
        component: () =>
          import(/* webpackChunkName: "Error" */ '../views/Detail')
      }
    ]
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '*',
    redirect: '/404'
  },
  {
    path: '/404',
    component: () =>
      import(/* webpackChunkName: "Error" */ '../views/Error.vue')
  }
]

// component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')

const router = new VueRouter({
  routes
})

// 路由拦截
router.beforeEach((to, from, next) => {
  const token = local.get('token')
  if (token) {
    next()
  } else {
    if (to.path === '/login') {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
